package gui.undo;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

@SuppressWarnings("serial")
public class UndoAction extends AbstractAction {
	private UndoManager undo = null;
	private RedoAction redoAction = null;

	public UndoAction(UndoManager undo, RedoAction redoAction) {
		super("Undo");
		this.undo = undo;
		this.redoAction = redoAction;
		setEnabled(false);
	}

	public void actionPerformed(ActionEvent e) {
		try {
			undo.undo();
		} catch (CannotUndoException ex) {
			System.out.println("Unable to undo: " + ex);
			ex.printStackTrace();
		}
		updateUndoState();
		redoAction.updateRedoState();
	}
	
	public void setRedoAction(RedoAction redoAction){
		this.redoAction = redoAction;
	}

	public void updateUndoState() {
		if (undo.canUndo()) {
			setEnabled(true);
			putValue(Action.NAME, undo.getUndoPresentationName());
		} else {
			setEnabled(false);
			putValue(Action.NAME, "Undo");
		}
	}
}